<template>
  <div>
    <div style="height: calc(100vh)" class="relation">
      <input
        class="search"
        placeholder="请输入城市名称"
        v-model="inputValue"
        @blur="searchCity"
        @keyup.enter="searchCity"
      />
      <RelationGraph
        ref="graphRef"
        style="background-color: transparent"
        :options="graphOptions"
        @node-click="onNodeClick"
        @line-click="onLineClick"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import RelationGraph from "relation-graph-vue3";
import axios from "axios";
var graph_json_data = [];
const nodeColors = [
  "#00008B", // 深蓝色
  "#2F4F4F", // 深灰色
  "#9400D3", // 深紫罗兰色

  "#FF8C00", // 深橙色
  "#FFD700", // 深黄色
  "#C71585", // 深粉色
  "#556B2F", // 深橄榄绿
  "#000080", // 深海军蓝
  "#080808", // 深宝石蓝
  "#7B3F00", // 深巧克力色
  "#A0522D", // 深咖啡色
  "#B03060", // 深玫瑰色

  "#CD5B45", // 深珊瑚色
  "#008B8B", // 深青色
  "#228B22", // 深森林绿
];
console.log(nodeColors);

const graphRef = ref(null);
const inputValue = ref("杭州市");
const graphOptions = {
  debug: false,
  backgroundColor: "#11162a",
  allowShowMiniToolBar: false,
  defaultNodeBorderWidth: 0,
  allowSwitchLineShape: false,
  defaultLineShape: 1,
  disableDragNode: false,
  moveToCenterWhenRefresh: false,
  zoomToFitWhenRefresh: false,
  useAnimationWhenRefresh: false,
  isMoveByParentNode: true, //子节点跟随
  layout: {
    layoutName: "force",
    maxLayoutTimes: 500000,
  },
  defaultJunctionPoint: "border",
};

onMounted(() => {
  showGraph();
});
const searchCity = async () => {
  showGraph();
};
const getJson = (data) => {
  let nodes = data.data.map((item) => {
    return {
      id: item.id,
      text: item.name,
      color: nodeColors[item.category],
    };
  });
  let lines = data.links.map((item) => {
    return {
      from: item.source,
      to: item.target,
      text: item.value,
    };
  });
  let obj = {
    nodes,
    lines,
  };
  return obj;
};
const getObj = async (area, id = "") => {
  let params = `?name=${area}`;
  if (id != "") {
    params = `?name=${area}&id=${id}`;
  }
  const response = await axios.get(
    `${process.env.VUE_APP_BASE_URL}/tupu/getNodeList${params}`
  );
  return response.data;
};
const showGraph = async () => {
  let data = await getObj(inputValue.value);
  let objData = await getJson(data);
  graph_json_data = {
    rootId: objData.nodes[0].id,
    nodes: objData.nodes,
    lines: objData.lines,
  };
  const graphInstance = graphRef.value.getInstance();
  if (graphInstance) {
    await graphInstance.setJsonData(graph_json_data);

    await graphInstance.moveToCenter();
    // // await graphInstance.zoomToFit();
    await graphInstance.setZoom(70);
  }
};
const setData = (array1, array2) => {
  console.log(array1, array2);
  // 创建一个映射，以第一个数组中对象的 'from' 和 'to' 属性组合作为键
  const uniqueMap = new Map(
    array1.map((item) => [`${item.from}-${item.to}`, true])
  );

  // 过滤第二个数组，去除与第一个数组重复的对象
  const filteredArray2 = array2.filter((item) => {
    const key = `${item.from}-${item.to}`;
    return !uniqueMap.has(key); // 如果映射中没有这个键，则对象不重复
  });

  return filteredArray2;
};
const onNodeClick = async (nodeObject, $event) => {
  console.log("onNodeClick:", nodeObject, $event);
  let data = await getObj(nodeObject.text, nodeObject.id);
  let objData = await getJson(data);
  const graphInstance = graphRef.value.getInstance();

  let lines = await setData(graph_json_data.lines, objData.lines);
  graph_json_data.lines = [...graph_json_data.lines, ...objData.lines];
  graphInstance.addNodes(objData.nodes);
  graphInstance.addLines(lines);
  // graphInstance.rootNode = graphInstance.getNodeById(jsonData.rootId);
  await graphInstance.doLayout(); // 使用graphOptions中设置的布局器布局
  await graphInstance.moveToCenter(); // 根据节点分布找到画面中心并居中
  await graphInstance.zoomToFit(); // 缩放到合适大小，以让所有节点可以在可见区域展示
  console.log(graphInstance.getGraphJsonData());
};

const onLineClick = (lineObject, linkObject, $event) => {
  console.log("onLineClick:", lineObject, linkObject, $event);
};
</script>

<style  lang="scss">
// .relation-graph .rel-node-peel{
//   transition: left 1s ease-out, top 1s  ease-out;
// }
.search {
  position: absolute;
  left: 50%;
  top: 150px;
  width: 640px;
  transform: translate(-50%);
  text-align: center;
  font-size: 18px;
  line-height: 46px;
  border-radius: 100px;
  border: none;
  outline: none;
  z-index: 999;
}

.relation {
  width: 100%;
  position: relative;
  background-color: #11162a;
}
</style>